/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package server.pluresdbclient;

import br.ufu.sdg12014.thriftpluresdb.client.Action;
import br.ufu.sdg12014.thriftpluresdb.client.TextInterface;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import server.piles.PilesData;

/**
 *
 * @author SergioPeres
 */
public class Client {
    public String      address;
    public final int   port = 9090;
    public Action      action;
    private TTransport transport = null;

    public Client(String s)
    {
        this.address = s;
        System.out.print("Connecting...");
        try
        {
            transport = new TSocket(address, port);
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);

            this.action = new Action(protocol);
        } catch (TTransportException x)
        {
            x.printStackTrace();
        }
        System.out.println(" [ OK ]");
    }

    public String execute(String command, String data)
    {
        int authenticationToken = action.getToken();
        String resp = "[INFO] Bye!";
        
        if (command.equals("exit"))
        {
            return resp;
        }
        int key = -1;
        switch(command)
        {
            case "begin":
                resp = action.begin(authenticationToken) ? "[OK]" : "[ERROR]" ;
                break;
            case "end":
                resp = action.end(authenticationToken);
                break;
            case "create":
                resp = action.create(authenticationToken, key, data);
                break;
            case "read":
                resp = action.read(authenticationToken, key);
                break;
            case "update":
                resp = action.update(authenticationToken, key, data);
                break;
            case "delete":
                resp = action.delete(authenticationToken, key);
                break;
            default: break;
        }
        this.transport.close();
        return resp;
    }
}
